<?php
/**
 * Created by IntelliJ IDEA.
 * User: luwei
 * Date: 2017/8/16
 * Time: 10:11
 */

namespace app\modules\api\models\kanjia;


use app\models\KjRecord;
use app\models\KjGoods;
use app\models\KjBargain;
use app\models\KjOrder;
use app\models\KjOrderComment;
use app\models\KjOrderDetail;
use app\modules\api\models\Model;
use yii\helpers\Html;
use app\models\User;

class OrderRecordForm extends Model
{
    public $cat_id;
    public $goods_id;
    public $bargain;
    public $user_id;
    public $price;
    public $store_id;
    public $createtime;
    public $bargains;
    public $record;
    public $bid;
    public $bargainprice;
    public $leftprice;

    public function rules()
    {
        return [
            [['goods_id',  'cat_id'], 'required','on'=>"saves"],
            [['bid'], 'required','on'=>"searchs"],
            [['goods_id', 'user_id', 'cat_id',  'createtime'], 'integer'],
            [['bargainprice', 'leftprice'], 'number'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'bid' => '发起砍价id'

        ];
    }

    /**
     * @return array|mixed
     * @throws \yii\db\Exception
     */
    public function save()
    {
        if (!$this->validate()){
            return $this->errorResponse;
        }
        $user_idss = \Yii::$app->user->id;
        $goods = KjGoods::findOne(['id' => $this->goods_id, 'cat_id' => $this->cat_id, 'is_delete' => 0, 'store_id' => $this->store_id]);
        $bargain = KjBargain::findOne(['goods_id' => $this->goods_id,'cat_id' => $this->cat_id,'user_id' => $this->user_id]);
        $record = KjRecord::findOne(['bid' => $bargain['id'],'user_id' => $user_idss]);

        if (empty($goods)){
            return [
                'code' => 1,
                'msg' => '活动删除或不存在',
            ];
        }
        if (time() > $goods["limit_time"]){
            return [
                'code' => 1,
                'msg' => '活动已结束',
            ];
        }
        if (!KjGoods::getNum($goods->id)) {
            return [
                'code' => 1,
                'msg' => '已无更多库存，无法继续帮其砍价',
            ];
        }

        if ($bargain["price"] <= $goods["lowprice"]) {
            return [
                'code' => 1,
                'msg' => 'TA的价格已经达到了最低价，不能继续砍啦！',
            ];
        }
        if ($bargain["user_id"] == $user_idss) {
            return [
                'code' => 1,
                'msg' => '不能帮自己砍价哦',
            ];
        }
        if ($user_idss == 0) {
            return [
                'code' => 1,
                'msg' => '用户信息读取失败，无法参与砍价',
            ];
        }
        $bargainprice = new OrderBargainForm();
        $bargainprice = $bargainprice->getBargainPrice($goods, $bargain["price"]);
        if (empty($record)) {
            $leftPrice = $bargain["price"] - $bargainprice;
            if ($leftPrice <= $goods["lowprice"]) {
                $leftPrice = $goods["lowprice"];
            }
            $bargains = KjBargain::find()
                ->andWhere([
                    'cat_id' => $this->cat_id,
                    'goods_id' => $this->goods_id,
                    'user_id' => $this->user_id,
                ])->one();

            if (!$bargains) {
                return [
                    'code' => 1,
                    'msg' => '此订单没有了',
                ];
            }
            $bargains->price = $leftPrice;
            $t = \Yii::$app->db->beginTransaction();
            if(!$bargains ->save()){
                $t->rollBack();
                return [
                    'code' => 1,
                    'msg' => '对不起，砍价失败',
                ];

            }

            $record = new KjRecord();
            $record->cat_id = $this->cat_id;
            $record->goods_id = $this->goods_id;
            $record->user_id = $user_idss;
            $record->bid = $bargain['id'];
            $record->bargainprice = $bargainprice;      //砍掉的金额
            $record->leftprice = $leftPrice;            //剩余的金额
            $record->createtime = time();
            if($record->save()){
                $t->commit();
            }else{
                $t->rollBack();
                return [
                    'code' => 1,
                    'msg' => '对不起，砍价失败',
                ];
            }
            $data = array(
                'bargainprice'=> $bargainprice,
                'leftPrice'=> $leftPrice,
                'bid'=> $bargain['id'],
                'cat_id' => $this->cat_id,
                'goods_id' => $this->goods_id,
            );
            return [
                'code' => 0,
                'msg' => '朋友帮您砍价成功',
                'data' => $data,
            ];

        } else {
            return [
                'code' => 1,
                'msg' => '你已经帮朋友砍过了哦',

            ];
        }


    }

    /**
     * @return array|mixed
     * 提供帮砍列表
     */
    public function search()
    {
        if (!$this->validate()){
            return $this->errorResponse;
        }
        $record = KjRecord::find()
            ->select([
                'u.avatar_url','u.nickname',
                'r.bid','r.id','r.bargainprice','r.leftprice','r.createtime',
            ])
            ->alias('r')
            ->where(['bid' => $this->bid,])
            ->leftJoin(['u'=>User::tableName()],'r.user_id=u.id')
            ->asArray()->all();

        if (!$record){
            return [
                'code' => 1,
                'msg' => '没有好友给您砍价',
            ];
        }

        return [
            'code' => 0,
            'data' => [
                'jia_record' => $record,

            ],
        ];

    }

}